<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="工单编号" prop="taskCode">
          <el-input
            v-model="queryParams.taskCode"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="工单类型" prop="productTypeId">
          <el-select
            v-model="queryParams.productTypeId"
            placeholder="请选择工单类型"
            clearable
          >
            <el-option
              v-for="dict in taskTypeList"
              :key="dict.typeId"
              :label="dict.typeName"
              :value="dict.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="工单编号" align="center" prop="taskCode" />
        <el-table-column label="设备编号" align="center" prop="innerCode" />
        <el-table-column label="工单类型" align="center" prop="taskType.typeName" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="addr" show-overflow-tooltip/>
        <el-table-column label="备注" align="center" prop="desc" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240px">
          <template #default="scope">
            <el-button 
              v-if="scope.row.productTypeId === 2" 
              link 
              type="primary" 
              icon="List" 
              @click="showReplenishmentDetails(scope.row)" 
              v-hasPermi="['manage:task:edit']"
            >补货清单</el-button>
            <el-button link type="primary" icon="Check" @click="completeTask(scope.row)" v-hasPermi="['manage:task:edit']">完成</el-button>
            <el-button link type="primary" icon="Close" @click="cancelTask(scope.row)" v-hasPermi="['manage:task:edit']">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 货道列表弹层 -->
      <BusinessReplenishmentListDialog
        :listVisible="listVisible"
        :detailData="detailData"
        @handleClose="closeReplenishmentDialog"
      ></BusinessReplenishmentListDialog>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
  
    </div>
  </template>
  
  <script setup name="Task">
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
  import { listTask, listTaskByUserId, getTaskDetails, updateTask,updateVm,updateVmLastSupplyTime} from "@/api/manage/task";
  import { getInfo } from '@/api/login'; 
  import { loadAllParams } from '@/api/page';
  import { listTaskType } from '@/api/manage/taskType';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import BusinessReplenishmentListDialog from '@/views/manage/task/components/business-replenishment-list-dialog.vue';
  import { getGoodsList, updateChannelCapacities } from "@/api/manage/channel";
  
  const { proxy } = getCurrentInstance();
  const { task_status, task_create_type } = proxy.useDict('task_status', 'task_create_type');
  
  const taskList = ref([]);
  const taskTypeList = ref([]);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const listVisible = ref(false);
  const detailData = ref([]);
  
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      taskCode: null,
      taskStatus: 2, // 工单状态设为进行中
      createType: null,
      innerCode: null,
      userId: null,
      userName: null,
      regionId: null,
      desc: null,
      productTypeId: null,
      assignorId: null,
      addr: null,
    },
    rules: {
      taskCode: [
        { required: true, message: "工单编号不能为空", trigger: "blur" }
      ],
    }
  });
  
  
  const { queryParams, form, rules } = toRefs(data);
  
  /** 查询工单列表 */
  async function getList() {
    loading.value = true;
  
    // 获取用户信息
    const userInfo = await getInfo(); 
  
    let response;
    if (userInfo.user.admin) { // 检查用户是否为超级管理员
      response = await listTask(queryParams.value); // 管理员使用 listTask
    } else {
      queryParams.value.userId = userInfo.user.userId; // 设置用户ID
      response = await listTaskByUserId(userInfo.user.userId, queryParams.value); // 非管理员使用 listTaskByUserId
    }
  
    // 更新工单列表和总数
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }
  
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  // 表单重置
  function reset() {
    form.value = {
      taskId: null,
      taskCode: null,
      taskStatus: 1,
      createType: null,
      innerCode: null,
      userId: null,
      userName: null,
      regionId: null,
      desc: null,
      productTypeId: null,
      assignorId: null,
      addr: null,
      createTime: null,
      updateTime: null
    };
    proxy.resetForm("taskRef");
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.taskId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  // 查询工单类型列表
  function getTaskTypeList() {
    const page = {
      ...loadAllParams
    };
    listTaskType(page).then((response) => {
      taskTypeList.value = response.rows;
    });
  }
   // 显示补货详情
   async function showReplenishmentDetails(row) {
    try {
      const response = await getTaskDetails(row.taskId);
      // 确保数据格式符合子组件的期望
      detailData.value = response.data.map(item => ({
        channelCode: item.channelCode,
        skuName: item.skuName || '--',
        expectCapacity: item.expectCapacity || 0
      }));
      listVisible.value = true;
      console.log('listVisible set to:', listVisible.value);
      console.log('detailData:', detailData.value);
    } catch (error) {
      console.error("获取补货详情失败:", error);
      ElMessage.error("获取补货详情失败");
    }
  }
  
  // 关闭补货详情对话框
  function closeReplenishmentDialog() {
    listVisible.value = false;
  }
  

// 完成工单
async function completeTask(row) {
  ElMessageBox.confirm('是否确认完成该工单?', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      if (row.productTypeId === 2) { // 补货工单
        const [taskDetails, currentChannels] = await Promise.all([
          getTaskDetails(row.taskId),
          getGoodsList(row.innerCode)
        ]);

        const currentCapacities = currentChannels.data.reduce((acc, channel) => {
          acc[channel.channelCode] = channel.currentCapacity;
          return acc;
        }, {});

        const channelsToUpdate = taskDetails.data.map(detail => ({
          innerCode: row.innerCode,
          channelCode: detail.channelCode,
          currentCapacity: (currentCapacities[detail.channelCode] || 0) + detail.expectCapacity,
          lastSupplyTime: new Date() // 添加最后补货时间
        }));
        
        console.log('Updating channel capacities:', channelsToUpdate);
        await updateChannelCapacities(channelsToUpdate);
        await updateVmLastSupplyTime({
          innerCode: row.innerCode
        });
      }

      // 更新工单状态
      const taskData = { 
        ...row, 
        taskStatus: 4, // 4 表示完成状态
      };
      await updateTask(taskData);

      ElMessage.success('工单已完成');
      getList(); // 刷新列表
    } catch (error) {
      console.error('完成工单失败:', error);
      let errorMessage = '完成工单失败';
      if (error.response && error.response.data && error.response.data.msg) {
        errorMessage += ': ' + error.response.data.msg;
      }
      ElMessage.error(errorMessage);
    }
  }).catch(() => {
    ElMessage.info('已取消完成工单');
  });
}
  
  getTaskTypeList();
  getList();
  </script>